#include "Semaphore.h"

namespace GPUCC
{
	namespace CPU
	{
		Semaphore::Semaphore(const unsigned int Count) : m_Semaphore(NULL), m_Count(Count)
		{
			this->m_Semaphore = CreateSemaphore(NULL, this->m_Count, this->m_Count, NULL);
		}

		Semaphore::~Semaphore()
		{
			if (this->m_Semaphore != NULL)
			{
				CloseHandle(this->m_Semaphore);
				this->m_Semaphore = NULL;
			}
		}

		unsigned int Semaphore::GetCount()
		{
			return (this->m_Count);
		}

		bool Semaphore::Get(unsigned int Timeout)
		{
			bool Result = false;

			DWORD WaitResult = WaitForSingleObject(this->m_Semaphore, Timeout);

			if (WaitResult == WAIT_OBJECT_0)
			{
				Result = true;
			}		

			return (Result);
		}

		bool Semaphore::Release(const unsigned int Count)
		{
			bool Result = false;
			
			if (ReleaseSemaphore(this->m_Semaphore, Count, NULL) == TRUE)
			{
				Result = true;
			}

			return (Result);
		}
	}
}